const Joi = require('@hapi/joi')
const Music = require('../models/music')

exports.v = {
  postMusic: {
    body: {
      title: Joi.string().required(),
      artist: Joi.string().required(),
      cover: Joi.string(),
      lyric: Joi.string(),
      src: Joi.string().required()
    }
  }
}

exports.getMusic = async function (ctx, next) {
  var data = await Music.find()
  ctx.body = data
}

exports.postMusic = async function (ctx, next) {
  var query = await Music.find({ src: ctx.request.body.src })
  if (query.length) {
    ctx.status = 200
    ctx.body = {
      success: false,
      message: 'music exists'
    }
  } else {
    var music = new Music(ctx.request.body)
    try {
      await music.save()
      ctx.body = {
        success: true,
        message: 'success'
      }
    } catch (err) {
      var details = []
      for (var error in err.errors) {
        details.push(err.errors[error].message)
      }
      ctx.status = 400
      ctx.body = {
        success: false,
        messages: 'invalid data',
        details: details
      }
    }
  }
}
